class_name UnitSeaUrchin
extends UnitBase


var allow_water_rects: Array[Rect2] = []


func init_by_data(data: UnitBaseData):
	super.init_by_data(data)
	
	for allow_water_name in unit_data.allow_move_water_ids:
		for index in range(level.all_waters.size()):
			if allow_water_name == level.all_waters[index].name:
				allow_water_rects.append(level.all_water_rects[index])
				break


func pick_new_wander_target():
	# 在矩形范围内随机目标点
	var x_offset = randf_range(-wander_width/2, wander_width/2)
	var y_offset = randf_range(-wander_height/2, wander_height/2)
	target_pos = home_position + Vector2(x_offset, y_offset)
	
	target_pos = GlobalUtils.clamp_position_to_rects(target_pos, allow_water_rects)
	
	# 下一次切换目标时间
	timer = randf_range(1.0, change_dir_time)
	

func process_approach(delta: float):
	if not attack_target: return
	
	if "approach_target" in attack_target:
		navigation_agent_2d.target_position = attack_target.approach_target.global_position
	else:
		navigation_agent_2d.target_position = attack_target.global_position
		
	if navigation_agent_2d.is_navigation_finished():
		return
	
	var next_pos = navigation_agent_2d.get_next_path_position()
	if not GlobalUtils.is_point_in_rects(next_pos, allow_water_rects):
		velocity = Vector2.ZERO
		return
	
	var dir = (next_pos - global_position).normalized()
	var target_velocity = dir * approach_speed
	if navigation_agent_2d.avoidance_enabled:
		navigation_agent_2d.set_velocity(target_velocity)
	else:
		_on_navigation_agent_2d_velocity_computed(target_velocity, delta)	
	
	
func play_wander_animation():
	animation_player.play("idle")
	
	
func process_speed_affect():
	var target_speed: float = normal_speed
	
	var debuff_numb = get_buff_by_name("debuff_numb")
	if debuff_numb:
		target_speed = target_speed * debuff_numb.numb_speed_scale
	
	speed = target_speed
